package kaindorfcompany.webshop.productmanagement.frontend.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kaindorfcompany.webshop.productmanagement.backend.access.DbAccess;
import kaindorfcompany.webshop.productmanagement.backend.exceptions.DbAccessFailureException;
import kaindorfcompany.webshop.productmanagement.frontend.servlets.util.ServletUtil;

/**
 * Servlet implementation class IngredientAddServlet
 */
@WebServlet("/admin/products/remove")
public class ProductRemoveServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ProductRemoveServlet() {
    }


    /**
     * Serve the system manager a view for adding a ingredient
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("productId");
        if (idStr == null) {
            ServletUtil.showGeneralError("Product id must be given", request, response);
            return;
        }
        int productId;
        try {
            productId = Integer.parseInt(idStr);
        } catch (NumberFormatException ex) {
            ServletUtil.showGeneralError("Illegal product id", request, response);
            return;
        }
        try {
            DbAccess.getInstance().removeProduct(productId);
        } catch (DbAccessFailureException ex) {
            ServletUtil.showGeneralError("Error with database: "+ex.getMessage(), request, response);
            log(null, ex);
            return;
        }
        ServletUtil.redirect(response, "/webshop/admin/products");
    }

    /**
     * Handle the request to add an ingredient by using the given data
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
